package cn.netty.example1;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.ReferenceCountUtil;

public class ClientHandler extends ChannelHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {


        try {
            ByteBuf byteBuf = (ByteBuf) msg;
            byte[] bytes = new byte[byteBuf.readableBytes()];
            byteBuf.readBytes(bytes);

            String message = new String(bytes, "UTF-8");

            System.out.println("form Server Message:"+message);
        } finally {
            //释放缓存
            ReferenceCountUtil.release(msg);
        }



    }


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {

        System.out.println("Client:channelActive");

        super.channelActive(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {

        System.out.println("ClientHandler exceptionCaught close");
        System.out.println(cause);
        ctx.close();
    }
}
